import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/user/Users.vue'
import Rights from '../components/power/Rights'
import Roles from '../components/power/Roles'
import GoodsCate from '../components/goods/Categories'
import Params from '../components/goods/Params.vue'
import GoodsList from '../components/goods/list'
import Add from '../components/goods/add'
import Edit from '../components/goods/edit'
import Orders from '../components/order/Order'
import Report from '../components/report/Report'

Vue.use(VueRouter)

const routes = [
	// 路由重定向：访问根目录，跳转到login
	{ path: '/', redirect: '/login' },
	// 添加login路由
	{ path: '/login', component: Login },
	// 添加home路由及welcome、users子路由（因为都是在home路由下）
	{
		path: '/home',
		component: Home,
		redirect: '/Welcome',
		children: [
			{ path: '/Welcome', component: Welcome },
			{ path: '/users', component: Users },
			{ path: '/rights', component: Rights },
			{ path: '/roles', component: Roles },
			{ path: '/categories', component: GoodsCate },
			{ path: '/params', component: Params },
			{ path: '/goods', component: GoodsList },
			{ path: '/goods/add', component: Add },
			{ path: '/goods/edit', name: 'edit', component: Edit },
			{ path: '/orders', component: Orders },
			{ path: '/reports', component: Report },
		],
	},
]

const router = new VueRouter({
	routes,
})

// TODO 挂载路由导航守卫
router.beforeEach((to, from, next) => {
	//to代表要访问的路径，from代表从哪个路径跳转过来，next代表一个函数
	// next()直接放行 ; next('/login')强行跳转到某个路径
	if (to.path === '/login') return next()
	// 获取token从sessionStorage
	const tokenStr = window.sessionStorage.getItem('token')
	// 如果没有token跳转登录页
	if (!tokenStr) return next('/login')
	// 如果有直接放行
	next()
})
export default router
